from rest_framework import viewsets, filters
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .models import WeeklyTodo
from .serializers import WeeklyTodoSerializer


class WeeklyTodoViewSet(viewsets.ModelViewSet):
    """周会待办事项视图集"""
    
    queryset = WeeklyTodo.objects.all()
    serializer_class = WeeklyTodoSerializer
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['closure', 'responsible_person']
    search_fields = ['task', 'responsible_person', 'remarks']
    ordering_fields = ['created_at', 'updated_at', 'planned_completion_time']
    ordering = ['-created_at']
    
    @action(detail=False, methods=['get'])
    def by_closure(self, request):
        """按闭环状态分组获取待办事项"""
        closure_status = request.query_params.get('status', None)
        if closure_status:
            todos = self.queryset.filter(closure=closure_status)
        else:
            todos = self.queryset.all()
        
        serializer = self.get_serializer(todos, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def by_person(self, request):
        """按责任人获取待办事项"""
        person = request.query_params.get('person', None)
        if person:
            todos = self.queryset.filter(responsible_person__icontains=person)
        else:
            todos = self.queryset.all()
        
        serializer = self.get_serializer(todos, many=True)
        return Response(serializer.data)
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取待办事项统计信息"""
        total = self.queryset.count()
        completed = self.queryset.filter(closure='闭环').count()
        pending = self.queryset.filter(closure='非闭环').count()
        
        return Response({
            'total': total,
            'completed': completed,
            'pending': pending,
            'completion_rate': round(completed / total * 100, 2) if total > 0 else 0
        })
    
    @action(detail=False, methods=['post'])
    def bulk_create(self, request):
        """批量创建待办事项"""
        data = request.data
        if not isinstance(data, list):
            return Response({'error': '数据必须是数组格式'}, status=400)
        
        serializer = self.get_serializer(data=data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)
